package us.mooresr.geartrack.client.core.desktop;

import java.util.List;

import us.mooresr.geartrack.client.core.presenter.ReturnItemPresenter;
import us.mooresr.geartrack.client.core.presenter.ReturnUiHandlers;
import us.mooresr.geartrack.shared.model.DatastoreObject;
import us.mooresr.geartrack.shared.model.Item;
import us.mooresr.geartrack.shared.model.Person;

import com.gwtplatform.mvp.client.ViewImpl;
import com.gwtplatform.mvp.client.ViewWithUiHandlers;
import com.google.gwt.core.client.GWT;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.inject.Inject;

public class DesktopReturnItemViewImpl extends ViewWithUiHandlers<ReturnUiHandlers> implements
		ReturnItemPresenter.MyView, ContentWidgetEventHandler {

	private final Widget widget;
	private final ContentWidget contentWidget;
	@UiField HTMLPanel contentPanel;
	private Item selectedItem;
	

	public interface Binder extends UiBinder<Widget, DesktopReturnItemViewImpl> {
	}

	@Inject
	public DesktopReturnItemViewImpl(final Binder binder) {
		widget = binder.createAndBindUi(this);
		contentWidget = GWT.create(ContentWidget.class);
		contentWidget.setTitle("Return an Item");
		contentWidget.setButtonText(1, "Check In");
		contentWidget.hideButton(2);
		contentWidget.hideButton(3);
		contentPanel.add(contentWidget);
		
		contentWidget.setHandler(this);
	}

	@Override
	public Widget asWidget() {
		return widget;
	}

	@Override
	public void onSelection(DatastoreObject selectedObject) {
		selectedItem = (Item) selectedObject;
		contentWidget.enableButton(1);
		
	}

	@Override
	public void onButton1Click() {
		// Check in button
		
		if (selectedItem == null) {
			return;
		}
		
		getUiHandlers().returnItem(selectedItem.getId());
		
	}

	@Override
	public void onButton2Click() {
		// Button 2 is not used
		
	}

	@Override
	public void onButton3Click() {
		// Button 3 is not used
		
	}

	@Override
	public void setItems(List<Item> list) {
		contentWidget.setListContents(list);
		clearSelection();
		
	}
	
	private void clearSelection() {
		selectedItem = null;
		contentWidget.clearSelection();
		contentWidget.disableButton(1);
	}


	@Override
	public void removeItem(Item item) {
		contentWidget.removeItemFromList(item);
		clearSelection();
		
	}
}
